/*
 * @Author: 杰编程 2306248989@qq.com
 * @Date: 2023-08-05 13:22:11
 * @LastEditors: 杰编程 2306248989@qq.com
 * @LastEditTime: 2023-08-05 19:53:15
 * @FilePath: /lesson24/2. tcp/tcp_client.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include <iostream>

using namespace std;
#include "err.hpp"
//#include <unistd.h>
#include <cstring>
#include <cerrno>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

void Usage(string pro)
{
    cout << "Useage\n\t" << pro << " serverip serverport\n"
         << endl;
}

// ./client serverip serverport
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(USE_ERR);
    }
    // 0. 提取服务端的信息
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(atoi(argv[2]));
    //server.sin_addr.s_addr = htonl(inet_addr(argv[1]));
    server.sin_addr.s_addr = inet_addr(argv[1]);

    // 1. 创建套接字，打开网络文件
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        std::cerr << "sockfd create error:" << strerror(errno) << std::endl;
        exit(SOCKET_ERR);
    }
    std::cout << "sockfd create successful: " << sockfd << std::endl;

    // 2. 尝试connect
    int cnt = 5; // 默认重试五次
    cout << "开始连接服务端" << endl;
    while (connect(sockfd, reinterpret_cast<struct sockaddr *>(&server), sizeof(server)) != 0)
    {
        cout << "连接服务端失败" << endl;
        sleep(1);
        cout << "正在尝试重新连接：" << cnt-- << endl;
        if (cnt <= 0)
            break;
    }
    if (cnt <= 0)
    {
        //close(sockfd);
        cerr << "连接失败！" << endl;
        exit(CONNECT_ERR);
    }
    else
    {
        // 3. 连接成功，开始通信
        cout << "连接成功，开始通信！" << endl;
        while (true)
        {
            string line;
            cout << "Please Enter>>>";
            getline(cin, line);
            // 3.1 发送数据
            write(sockfd, line.c_str(), line.size());
            // 3.2 接受数据
            char buffer[1024];
            ssize_t n = read(sockfd, buffer, sizeof(buffer) - 1);
            if (n > 0)
            {
                buffer[n] = 0;
                cout << "server echo>>>" << buffer << endl;
            }
            else if (n == 0)
            {
                cout << "server quit..." << endl;
                break;
            }
            else
            {
                cerr << "read error..." << endl;
                break;
            }
        }
    }

    cout << "client" << endl;
    return 0;
}
